package com.swotxu.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;

/**
 * @Date: 2022/5/1 22:33
 * @Author: swotXu
 */
public class RedisUtils {
    /** Lua脚本 - 比较并删除 */
    public static final String SCRIPT_COMPARE_DELETE = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    StringRedisTemplate stringRedisTemplate;

    public RedisUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 比较并删除
     * @param key   redis-key
     * @param value 比较值
     * @return  1-成功 0-失败
     */
    public Long compareDelete(String key, Object value) {
        return stringRedisTemplate.execute(new DefaultRedisScript<>(SCRIPT_COMPARE_DELETE, Long.class), Collections.singletonList(key), value);
    }
}
